#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "config.h"
#include <QPixmap>
#include <QPaintEvent>
#include <QPainter>
#include <QKeyEvent>
#include <random>
#include <QDebug>
#include <QDateTime>
#include <QRect>
#include <QMessageBox>



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m(new map)
    , timer(new QTimer(this))
    , hero(new main_plane), k_up(0),k_down(0),k_right(0),k_left(0)
{
    setFixedSize(GAME_WINDOW_WIDE,GAME_WINDOW_HIGH);
    ui->setupUi(this);
    setWindowTitle(GAME_WINDOW_TITLE);
    QPixmap main_window_icon(MAIN_ICON);
    setWindowIcon(main_window_icon);

    connect(timer, &QTimer::timeout, this, &MainWindow::onTimerTimeout);
    get_bad_p = 0;
    timer->setInterval(5);
    timer->start();
    life_bar = new QProgressBar;
    // 设置进度条的最小值和最大值
    scores = 0;
    lever = 0;

}

MainWindow::~MainWindow()
{
    delete ui;
    delete m;
    delete timer;
}



void MainWindow::paintEvent(QPaintEvent *event)
{   QPainter p(this);


    Q_UNUSED(event);

    p.drawImage(0,m->image1_set-GAME_WINDOW_HIGH,m->back_image1);
    p.drawImage(0,m->image2_set,m->back_image2);
    p.drawImage(hero->m_x,hero->m_y,hero->plane);
    hero->plane_rect.moveTo(hero->m_x,hero->m_y);

    paint_bullet(p);
    // 设置字体
    QFont font("Arial", 20, QFont::Bold, true);
    p.setFont(font);

    // 设置颜色
    QPen pen(QColor(0, 128, 255)); // 蓝色
    p.setPen(pen);
    QRect rect(GAME_WINDOW_WIDE-150, GAME_WINDOW_HIGH-100, 150, 100);
    p.drawText(rect,Qt::AlignCenter,"弹药"+QString::number(hero->bl_m1_num));

    add_bad_plane();
    move_bad_plane(p);
    set_bar(p);
    set_scores(p);
}



void MainWindow::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
               case Qt::Key_Up:
                   k_up = 1;
                   break;
               case Qt::Key_Down:
                   k_down = 1;
                   break;
               case Qt::Key_Left:
                   k_left = 1;
                   break;
               case Qt::Key_Right:
                   k_right = 1;
                   break;
               case Qt::Key_S:
                   hero->shoot();
                   break;
    }
}

void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
    switch (event->key()) {
               case Qt::Key_Up:
                   k_up = 0;
                   break;
               case Qt::Key_Down:
                   k_down = 0;
                   break;
               case Qt::Key_Left:
                   k_left = 0;
                   break;
               case Qt::Key_Right:
                   k_right = 0;
                   break;
    }
}

void MainWindow::paint_bullet(QPainter &p)
{
    for(auto temp : hero->list_bl){
        p.drawImage(temp->m_x,temp->m_y,temp->bl);
        temp->bl_R.moveTo(temp->m_x,temp->m_y);
    }
}

void MainWindow::add_bad_plane()
{
    // 创建随机数设备
        std::random_device rd;
        // 结合随机设备和当前时间的毫秒数创建种子序列
        std::seed_seq seed{rd(), static_cast<unsigned int>(QDateTime::currentMSecsSinceEpoch())};
        // 使用种子序列初始化随机数引擎
        std::mt19937 gen(seed);

        // 定义随机数分布，生成 0 到 100 之间的整数
        int top = 200;
        if(lever<5){
            top = 200-scores*2;
        }else if(lever>5&&lever<10){
            top = 150 - scores;
        }else if(lever>10){
            top = 50-lever/10;
        }
        std::uniform_int_distribution<> dis(0, top);
    int randomInt = dis(gen);
    get_bad_p = randomInt;
    qDebug()<<randomInt;
    if(get_bad_p == 1){
        bad_plane1 temp;
        bad_p1.push_back(temp);
    }
}

void MainWindow::move_bad_plane(QPainter &p)
{
    for (auto it = bad_p1.begin(); it != bad_p1.end(); ) {
        it->m_y += it->m_speed;
        if (it->m_y > GAME_WINDOW_HIGH) {
            it = bad_p1.erase(it); // 使用 erase 的返回值更新迭代器
        } else {
            qDebug()<<it->m_x;
            p.drawImage(it->m_x, it->m_y, it->plane);
            it->plane_rect.moveTo(it->m_x, it->m_y);
            ++it;
        }
    }
}

void MainWindow::QRect_detection()
{
    for (auto it1 = hero->list_bl.begin(); it1 != hero->list_bl.end(); ) {
        bool isHit = false;
        for (auto it2 = bad_p1.begin(); it2 != bad_p1.end(); ) {
            if ((*it1)->bl_R.intersects(it2->plane_rect)) {
                // 发生碰撞，处理碰撞逻辑
                it2->life -= (*it1)->damage;
                if (it2->life <= 0) {
                    it2 = bad_p1.erase(it2); // 使用 erase 的返回值更新迭代器
                    scores++;
                    get_reward();
                } else {
                    ++it2;
                }
                delete(*it1);
                it1 = hero->list_bl.erase(it1);
                isHit = true;
                break; // 子弹已经击中敌机，跳出内层循环
            } else {
                ++it2;
            }
        }
        if (!isHit) {
            ++it1; // 如果子弹未击中敌机，移动到下一个子弹
        }
    }

    //检测主角和敌机的碰撞
    for (auto it2 = bad_p1.begin(); it2 != bad_p1.end(); ) {
        if (hero->plane_rect.intersects(it2->plane_rect)) {
            hero->life -= it2->life;
            if(hero->life <= 0){
               QMessageBox::information(this,"提示","游戏结束");
               restart();
            }
            it2 = bad_p1.erase(it2);
            scores++;
            get_reward();
        } else {
            ++it2;
        }
    }

}

void MainWindow::restart()
{
    k_up = 0;
    k_down = 0;
    k_right = 0;
    k_left = 0;
    delete hero;
    hero = new main_plane;
    scores = -1;
}

void MainWindow::set_bar(QPainter &p)
{
    life_bar->setRange(0, 10);
        // 设置当前进度
    life_bar->setValue(hero->life);
    // 定义进度条的位置和大小
            int barX = 20;
            int barY = 20;
            int barWidth = 128;
            int barHeight = 20;

            // 绘制进度条的背景
            p.setBrush(Qt::lightGray);
            p.drawRect(barX, barY, barWidth, barHeight);

            // 计算进度条中已完成部分的宽度
            int progressWidth = 128*(hero->life/10.0);

            // 绘制进度条的进度部分
            p.setBrush(Qt::blue);
            p.drawRect(barX, barY, progressWidth, barHeight);

            // 绘制进度条的边框
            p.setBrush(Qt::NoBrush);
            p.setPen(Qt::black);
            p.drawRect(barX, barY, barWidth, barHeight);
}

void MainWindow::set_scores(QPainter &p)
{
    // 设置字体
    QFont font("Arial", 20, QFont::Bold, true);
    p.setFont(font);

    // 设置颜色
    QPen pen(QColor(0, 128, 255)); // 蓝色
    p.setPen(pen);
    QRect rect(GAME_WINDOW_WIDE-150, 0, 150, 100);
    p.drawText(rect,Qt::AlignCenter,"得分："+QString::number(scores));
    lever = scores/10;
}

void MainWindow::get_reward()
{
    // 创建随机数设备
        std::random_device rd;
        // 结合随机设备和当前时间的毫秒数创建种子序列
        std::seed_seq seed{rd(), static_cast<unsigned int>(QDateTime::currentMSecsSinceEpoch())};
        // 使用种子序列初始化随机数引擎
        std::mt19937 gen(seed);

        // 定义随机数分布，生成 0 到 100 之间的整数
        std::uniform_int_distribution<> dis(0, 10);
        int randomInt = dis(gen);

        switch (randomInt) {
        case 0:
            if(hero->life<10)hero->life++;
            break;
        case 1:
            hero->bl_m1_num += 5;
            break;
        case 2:
            hero->m_speed++;
            break;
        case 3:
            hero->bl_m1_num += 1;
            break;
        case 4:
            hero->bl_m1_num += 3;
            break;
        }
}


void MainWindow::onTimerTimeout()
{
    m->image1_set = (m->image1_set+1)%GAME_WINDOW_HIGH;
    m->image2_set = (m->image2_set+1)%GAME_WINDOW_HIGH;

    if(k_right == 1) {
        if(hero ->m_x + 1 != GAME_WINDOW_WIDE-hero->plane.width()){
            hero->m_x += 1;
        }
    }
    if(k_down == 1) {
        if(hero ->m_y + 1 != GAME_WINDOW_HIGH-hero->plane.height()){
            hero->m_y += 1;
        }
    }
    if(k_up == 1) {
        if(hero ->m_y - 1 != 0){
            hero->m_y -= 1;
        }
    }
    if(k_left == 1) {
        if(hero ->m_x - 1 != 0){
            hero->m_x -= 1;
        }
    }
    //更新子弹位置
    for(auto temp = hero->list_bl.begin();temp != hero->list_bl.end();temp++){
        (*temp)->m_y -= (*temp)->speed;
        if((*temp)->m_y +(*temp)->bl.height() == 0){
            hero->list_bl.erase(temp);
            delete *temp;
        }
    }
    QRect_detection();

    QMainWindow::update();
}



